How to use the XOR (^) operator In Javascript
In this method, If the operands have different boolean values, the XOR operator returns true; otherwise, it returns false.
Example: We are using XOR (^) operator.
HTML
< html > < head > < title > How to toggle a boolean using XOR in JavaScript? </ title > </ head > < body > < h1 style = "color: green" > w3wiki </ h1 > < b > How to toggle a boolean using XOR in JavaScript? </ b > < p > The boolean is toggled whenever the button is pressed. </ p > < p > See the console for the output </ p > < button onclick = "toggle()" > Toggle Bool </ button > < p id = "toggled" > </ p > < script > let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = testBool ^ true; let text = document.getElementById('toggled') text.innerHTML = testBool ? "true" : "false" // console.log('Toggled bool is', testBool); } </ script > </ body > </ html > |
Output:
How to toggle a boolean using JavaScript ?
A boolean value can be toggled in JavaScript by using two approaches which are discussed below:
Table of Content
- Using the logical NOT operator
- Using the ternary operator
- Using the XOR (^) operator